package com.hongdee.crm.carConfig.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.hongdee.common.dao.IHibernateDao;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.carConfig.dao.ITCrmCarRefDao;
import com.hongdee.crm.carConfig.entity.TCrmCarRef;
import com.hongdee.crm.carConfig.service.ITCrmCarRefService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by My on 2017/2/20.
 */
@Service
public class TCrmCarRefServiceImpl implements ITCrmCarRefService {
    @Autowired
    private IHibernateDao iHibernateDao;
    private String tabName = "T_CRM_CAR_REF";
    private String entity = "TCrmCarRef";
    private String tabUser = "T_BC_USER";
    private List<String> deptList;
    @Autowired
    private ITCrmCarRefDao itCrmCarRefDao;

    /**
     * @param data TCrmCarRef 实体类
     * @return Map
     * @throws Exception
     * @desc 车辆分配
     * @author 徐钦勇
     */
    @Override
    public TCrmCarRef saveOrUpdate(TCrmCarRef data) throws Exception {
        if(data.getId()==null){
            if(this.itCrmCarRefDao.listByTableName("T_CRM_CAR_REF","u_id",data.getuId()).size()>0){
                throw new Exception("人员已分配车辆，请给其他人员分配！");
            }
        }
        if (!data.getValue().isEmpty()) {
            String[] value = data.getValue().split(",");
            String type = data.getType();
            String role = data.getRoleId();
            if (type.isEmpty()) {
                throw new Exception("请选择分配类型！");
            } else {
                for (String i : value) {
                    List params = new ArrayList();
                    String sql = "select * from " + tabName + " where type= ? and role_id = ? and find_in_set(?,value)";
                    params.add(type);
                    params.add(role);
                    params.add(i);
                    if (data.getId() != null) {
                        sql += " and id !=  ?";
                        params.add(data.getId());
                    }
                    if (!this.itCrmCarRefDao.page(sql, params.toArray(), "0", "50").get("total").equals("0")) {
                        throw new Exception("车辆已经分配！");
                    }
                }
            }
        }else if(!data.getType().equals("0")){
            throw new Exception("请分配车辆！");
        }
        return (TCrmCarRef) this.itCrmCarRefDao.saveOrUpdate(data);
    }

    /**
     * 公司下所有用户
     *
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> uesrCombo(String uid) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        List params = new ArrayList();
        //取 companyId下的所有部门ID
        List<String> deptList = new ArrayList<>();
        deptList.add(companyId);
        buildDeptChild(deptList,companyId);
        String sql = " select id,u_name from " + tabUser + " where o_id in ( ";
        for (String oid : deptList) {
            sql += " ? , ";
            params.add(oid);
        }
        sql += " '' ) and id not in ( select u_id from " + tabName + " )";
        List<Map<String, Object>> user = this.itCrmCarRefDao.list(sql, params.toArray());
        List<Map<String, Object>> combo = new ArrayList<>();
        Map<String, Object> temp;
        for (Map<String, Object> uMap : user) {
            temp = new HashMap<>();
            temp.put("label", String.valueOf(uMap.get("uName")));
            temp.put("value", uMap.get("id"));
            combo.add(temp);
        }
        return combo;
    }

    /**
     * @param start 当前页面
     * @param limit 页面大小
     * @param name  角色姓名
     * @param group 分组
     * @return Map
     * @throws Exception
     * @desc 分页查询
     * @author 徐钦勇
     */
    @Override
    public Map page(String start, String limit, String name, String group, String type, String oid) throws Exception {
        String sql = "select a.id,b.u_name,a.group_code,a.type,c.r_name,c.r_desc,a.value,a.company_id,a.status from " +
                "T_CRM_CAR_REF a " +
                "LEFT JOIN t_bc_user b on a.u_id=b.id " +
                "LEFT JOIN t_bc_role c on a.role_id=c.id  where 1=1 ";
        List params = new ArrayList();
        if (!name.isEmpty()) {
            sql += " and u_name like ? ";
            params.add("%" + name + "%");
        }
//        if (!group.isEmpty()) {
//            sql += " and group_code = ? ";
//            params.add(group);
//        }
        if(!type.isEmpty()){
            sql+=" and role_id = ? ";
            params.add(type);
        }
        if (!oid.isEmpty()) {
            sql += " and company_id = ? ";
            params.add(oid);
        }
        return this.itCrmCarRefDao.page(sql, params.toArray(), start, limit);
    }

    /**
     * @param id     主键
     * @param status 状态
     * @return Map
     * @throws Exception
     * @desc 启用停用
     * @author 徐钦勇
     */
    @Override
    public void update(String id, String status) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择记录");
        }
        String hql = "update " + entity + " set status = :status where id = :id ";
        Map params = new HashMap();
        params.put("id", id);
        params.put("status", status);
        this.itCrmCarRefDao.update(hql, params);
    }

    /**
     * @param id 主键
     * @return Map
     * @throws Exception
     * @desc 车辆分配明细
     * @author 徐钦勇
     */
    @Override
    public Map info(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择记录");
        }
        String sql = "select * from " + tabName + " where id = ? ";
        return this.itCrmCarRefDao.info(sql, new Object[]{id});
    }

    /**
     * @param start 当前页面
     * @param limit 页面大小
     * @param role
     * @return Map
     * @throws Exception
     * @desc 人员分页查询
     * @author 徐钦勇
     */
    @Override
    public Map employeePage(String start, String limit, String role) throws Exception {
        String sql = "select * from " + tabName + " where 1=1 ";
        List params = new ArrayList();
//        if(!TokenUtil.getCompanyId(uid).isEmpty()){
//            sql+=" and company_id = ? ";
//            params.add(TokenUtil.getCompanyId(uid));
//        }
        return this.itCrmCarRefDao.page(sql, params.toArray(), start, limit);
    }

    /**
     * 公司下所有的角色
     */
    @Override
    public List<Map<String, Object>> roleCombo(String uid) throws Exception {

        //获取当前人员部门
        String oId = TokenUtil.getDeptId(uid);
        String companyId = TokenUtil.getCompanyId(uid);
        List params = new ArrayList();
        //查询所有角色，公司，是否应用下级部门
        String resSql = "select * from t_bc_role where r_status='1' ";
        if (!"0".equals(oId)) {
            List<Map<String, Object>> resList = this.itCrmCarRefDao.list(resSql, params.toArray());
            List list = new ArrayList();
            resSql += " and ( id in ( ";
            for (Map resMap : resList) {
                //判断是否应用下级
                switch (resMap.get("hasChild").toString()) {

                    //未应用下级，判断是否是当前部门相同
                    case "0": {
                        //当前部门与查询已有部门一致
                        if (oId.equals(resMap.get("oId").toString())) {
                            resSql += " ?, ";
                            params.add(resMap.get("id").toString());
                        }
                    }
                    break;
                    //应用下级，判断下级部门及当前公司是否与本公司相同
                    case "1": {
                        //登录者所有上级部门及公司
                        list = parent(oId, list);
                        int i = 0;
                        for (Object obj : list) {
                            //判断本部门是否在上级部门及公司里
                            if (obj.toString().equals(resMap.get("oId").toString())) {
                                i++;
                            }
                        }
                        //本部门在上级部门及公司内
                        if (i > 0) {
                            resSql += " ?, ";
                            params.add(resMap.get("id").toString());
                        }
                    }
                    break;
                }
            }
            resSql += " '' ) or o_id = ? ) ";
            params.add(companyId);
        }

        List<Map<String, Object>> role = this.itCrmCarRefDao.list(resSql, params.toArray());
        List<Map<String, Object>> combo = new ArrayList<>();
        Map<String, Object> temp;
        for (Map<String, Object> uMap : role) {
            temp = new HashMap<>();
            temp.put("label", String.valueOf(uMap.get("rName")));
            temp.put("value", uMap.get("id"));
            combo.add(temp);
        }
        return combo;
    }

    /**
     * 根据角色类型去查对应的人
     *
     * @param type
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> queryUserCombo(String uid,String type, String companyId) throws Exception {
        if("".equals(companyId)){
            companyId=TokenUtil.getCompanyId(uid);
        }
        //取 companyId下的所有部门ID
        List<String> deptList = new ArrayList<>();
        deptList.add(companyId);
        buildDeptChild(deptList,companyId);
        //取得了所有人部门ID
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT                              ");
        sqlBuf.append(" 	u.id,                           ");
        sqlBuf.append(" 	u.u_name,                       ");
        sqlBuf.append(" 	u.u_code                         ");
        sqlBuf.append(" FROM                                ");
        sqlBuf.append(" 	t_bc_user u,                    ");
        sqlBuf.append(" 	t_bc_role_user tr               ");
        sqlBuf.append(" WHERE                               ");
        sqlBuf.append(" 	u.id = tr.u_id                  ");
        sqlBuf.append(" AND tr.r_type = '0'                 ");
        sqlBuf.append(" AND u.id<>'0'                       ");
        sqlBuf.append(" AND u.u_status = '1'                ");
        sqlBuf.append(" AND tr.r_id= ?                      ");
        sqlBuf.append(" and u.o_id in  (                     ");
        for (String oid : deptList) {
            sqlBuf.append("?,");
        }
        sqlBuf.append(" '' )                  ");
        deptList.add(0, type);
        List<Map<String, Object>> users = this.itCrmCarRefDao.list(sqlBuf.toString(), deptList.toArray());
        List<Map<String, Object>> combo = new ArrayList<>();
        Map<String, Object> temp;
        for (Map<String, Object> uMap : users) {
            temp = new HashMap<>();
            temp.put("label", String.valueOf(uMap.get("uName")) + "(" + String.valueOf(uMap.get("uCode")) + ")");
            temp.put("value", uMap.get("id"));
            combo.add(temp);
        }
        return combo;
    }

    /**
     * 公司下所有人员
     * 2017/04/12
     * 徐钦勇
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> queryUserCombo1(String uid, String companyId) throws Exception {
        deptList = new ArrayList<>();

        //取得了所有人部门ID
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT                              ");
        sqlBuf.append(" 	u.id,                           ");
        sqlBuf.append(" 	u.u_name,                       ");
        sqlBuf.append(" 	u.u_code                         ");
        sqlBuf.append(" FROM                                ");
        sqlBuf.append(" 	t_bc_user u                    ");
        sqlBuf.append(" WHERE  u.id<>'0' "                   );
        sqlBuf.append(" AND u.u_status = '1'                ");
        if(TokenUtil.isCompanyAdmin(uid)) {
            deptList.add(companyId);
            buildDeptChild(deptList,companyId);
            if (deptList.size() > 0) {
                sqlBuf.append(" and u.o_id in ( ");
                for (String oid : deptList) {
                    sqlBuf.append(" ? , ");
                }
                sqlBuf.append(" '' ) ");
            }
        }else{
            sqlBuf.append(" and u.id=? ");
            deptList.add(uid);
        }
        List<Map<String, Object>> users = this.itCrmCarRefDao.list(sqlBuf.toString(), deptList.toArray());
        List<Map<String, Object>> combo = new ArrayList<>();
        Map<String, Object> temp;
        for (Map<String, Object> uMap : users) {
            temp = new HashMap<>();
            temp.put("label", String.valueOf(uMap.get("uName")) + "(" + String.valueOf(uMap.get("uCode")) + ")");
            temp.put("value", uMap.get("id"));
            combo.add(temp);
        }
        return combo;
    }

    /**
     * @Name: 部门下所有人员
     * @Author: Liu XiaoLong
     * @Date: 2018/3/9 17:16
     * @Remark:
     */
    @Override
    public List<Map<String, Object>> queryOrganUserCombo(String uid, String companyId) throws Exception {
        deptList = new ArrayList<>();
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT                              ");
        sqlBuf.append(" 	u.id,                           ");
        sqlBuf.append(" 	u.u_name,                       ");
        sqlBuf.append(" 	u.u_code                         ");
        sqlBuf.append(" FROM                                ");
        sqlBuf.append(" 	t_bc_user u                    ");
        sqlBuf.append(" WHERE  u.id<>'0' "                   );
        sqlBuf.append(" AND u.u_status = '1'                ");
        if(TokenUtil.isCompanyAdmin(uid)) {

               Map orgInfo = TokenUtil.getOrgInfo(uid);
                Map deptMap = TokenUtil.getDept(uid);
                //String oPid = (String) deptMap.get("oPId");
                boolean isStoreSa = false;
                String orgStoreId = "";
                String oArea = "";
                if(deptMap != null){
                    if(deptMap.get("oPId").equals("8a9aa28460026f310160059c8dd804b2")){ // 属于门店角色
                        orgStoreId = (String) orgInfo.get("deptId");
                        isStoreSa = true;
                    }
                    if(deptMap.get("oPId").equals("401e8482626facfb01626fbf26ee0624")){ // 属于区域经理角色
                        oArea = (String) deptMap.get("oAreaSecond"); // 获取区域
                    }

                }



            if(!isStoreSa){ // 如果不是门店及以下权限，则都显示

                if(!oArea.equals("")){ // 如果为区域经理角色
                    String oIdByAreaSql = "select id from t_bc_organ where o_area_second = ? and o_p_id = '8a9aa28460026f310160059c8dd804b2' ";
                    List oIdArea = itCrmCarRefDao.list(oIdByAreaSql,oArea);
                    if (oIdArea.size() > 0) {
                        sqlBuf.append(" and u.o_id in ( ");
                        for (Object oid : oIdArea) {
                            sqlBuf.append(" ? , ");
                            deptList.add(((Map)oid).get("id").toString());
                        }
                        sqlBuf.append(" '' ) ");
                    }
                }
                else {
                    deptList.add(companyId);
                    buildDeptChild(deptList,companyId);
                    if (deptList.size() > 0) {
                        sqlBuf.append(" and u.o_id in ( ");
                        for (String oid : deptList) {
                            sqlBuf.append(" ? , ");
                        }
                        sqlBuf.append(" '' ) ");
                    }
                }
            }
            else { // 如果是门店sa，则只显示此门店下的
                sqlBuf.append(" and u.o_id = ? ");
                deptList.add(orgStoreId);
            }
        }else{
            sqlBuf.append(" and u.id=? ");
            deptList.add(uid);
        }
        List<Map<String, Object>> users = this.itCrmCarRefDao.list(sqlBuf.toString(), deptList.toArray());
        List<Map<String, Object>> combo = new ArrayList<>();
        Map<String, Object> temp;
        for (Map<String, Object> uMap : users) {
            temp = new HashMap<>();
            temp.put("label", String.valueOf(uMap.get("uName")) + "(" + String.valueOf(uMap.get("uCode")) + ")");
            temp.put("value", uMap.get("id"));
            combo.add(temp);
        }
        return combo;

    }



    private List<Map<String, Object>> buildDeptParent(List<String> deptList,List<Map<String, Object>> paranet) throws Exception {
        if (paranet.size() == 0) {
            return paranet;
        }
        String pId;
        for (Map<String, Object> temp : paranet) {
            pId = String.valueOf(temp.get("id"));
            List<Map<String, Object>> childList = buildDeptChild(deptList,pId);
            temp.put("child", childList);
            deptList.add(pId);
        }
        return paranet;
    }

    @Override
    public List<Map<String, Object>> buildDeptChild(List<String> deptList,String opId) throws Exception {
        String sqlStr = "select * from t_bc_organ  where o_p_id = ? ";
        List<Map<String, Object>> child = this.itCrmCarRefDao.list(sqlStr, opId);
        return buildDeptParent(deptList,child);
    }

    /**
     * @param objId 删除的主键
     * @return Map
     * @throws Exception
     * @desc
     * @author 徐钦勇
     */
    @Override
    public boolean deleteById(String objId) throws Exception {
        String hql = "delete from TCrmCarRef where id = :id";
        Map params = new HashMap();
        params.put("id", objId);
        this.iHibernateDao.executeHqlWithParams(hql, params);
        return true;
    }

    /****
     * 查询上一层次的部门
     */
    String ORG_PARENT_SQL = " select o_p_id from t_bc_organ where id = ? ";
    private List parent(String oid, List resIds) throws Exception {
        Map temp = this.itCrmCarRefDao.info(ORG_PARENT_SQL, oid);
        if (temp == null || temp.size() == 0) {
            return resIds;
        } else {
            oid = String.valueOf(temp.get("oPId"));
            resIds.add(oid);
            return parent(oid, resIds);
        }
    }
}
